import React,{Component, PropTypes} from 'react';
import ReactDom,{findDOMNode} from 'react-dom';
import $ from '../util/jquery-3.1.0.min.js';
import TouchSwiper from '../util/touchEvents';
import './carousel.less';


var SliderItem = React.createClass({
    render(){
        let {items, nowLocal} = this.props;
        let itemNodes = this.props.items.map((obj,idx)=>{
            return (
                <li className={`slider-item ${idx === this.props.nowLocal ? "active":""}`} key={idx}>
                    <img src={obj.url} alt=""/>
                </li>
            )
        });

        let count = this.props.items.length;
        let width = 100 * count + '%';
        let position = (this.props.nowLocal * 100 + '%');
        return (
            <ul className="carousel-inner" style={{width:width,left:'-' + position}}>
                {itemNodes}
            </ul>
        )
    }
});

var SliderDots = React.createClass({

    handleDotClick(i) {
        var option = i - this.props.nowLocal;
        this.props.turn(option);
    },

    render() {
        let dotNodes = [];
        let { count, nowLocal, turn} = this.props;
        for(let i = 0; i < count; i++) {
            dotNodes[i] = (
                <li
                    key={'dot' + i}
                    className={`slider-dot ${i === this.props.nowLocal ? "active":""}`}
                    onClick={this.handleDotClick.bind(this, i)}>
                </li>
            );
        }
        return (
            <div className="carousel-indicators">
                {dotNodes}
            </div>
        );
    }
});

var SliderArrows = React.createClass({

    handleArrowClick(option) {
        this.props.turn(option);
    },

    render() {
        let {turn} = this.props;
        return (
            <div className="slider-arrows-wrap">
                <span
                    className="slider-arrow slider-arrow-left"
                    onClick={this.handleArrowClick.bind(this, -1)}>
                    -
                </span>
                <span
                    className="slider-arrow slider-arrow-right"
                    onClick={this.handleArrowClick.bind(this, 1)}>
                    +
                </span>
            </div>
    );
    }
});

var Carousel = React.createClass({
    propTypes: {
        autoplay: React.PropTypes.bool,
        pause: React.PropTypes.bool,
        dots: React.PropTypes.bool,
        arrows: React.PropTypes.bool,
        speed: React.PropTypes.number,
        delay: React.PropTypes.number,
        items: React.PropTypes.array   //轮播对象,由父组件传入数据列表，必须包含轮播图片3个字段，src、alt及商品id
    },
    getInitialState(){
        return {
            nowLocal: 0,
            startTx: 0,
            startTy: 0,
            isTouchMove: false,
            direction: ''
        }
    },

    // 向前向后多少
    turn(n) {
        var _n = this.state.nowLocal + n;
        if(_n < 0) {
            _n = _n + this.props.items.length;
        }
        if(_n >= this.props.items.length) {
            _n = _n - this.props.items.length;
        }
        this.setState({nowLocal: _n});
    },

    // 开始自动轮播
    goPlay() {
        if(this.props.autoplay) {
            this.autoPlayFlag = setInterval(() => {
                this.turn(1);
            }, this.props.delay * 1000);
        }
    },

    autoPlayFlag: null,

    componentDidMount: function () {
        this.goPlay();
    },

    touchStart: function (e) {
        var touches = e.touches[0];

        this.state.startTx = touches.clientX;
        this.state.startTy = touches.clientY;
        this.state.isTouchMove = false;
    },
    touchMove:function (e) {
        this.state.isTouchMove = true;
        e.preventDefault();
    },
    touchEnd: function (e) {
        if (!this.state.isTouchMove) {
            return;
        }

        var touches = e.changedTouches[0],
            endTx = touches.clientX,
            endTy = touches.clientY,
            distanceX = this.state.startTx - endTx,
            distanceY = this.state.startTy - endTy,
            isSwipe = false;

        if(Math.abs(distanceX) >= Math.abs(distanceY)){
            if (distanceX > 20){
                clearInterval(this.autoPlayFlag);
                this.turn(1);
                this.autoPlayFlag = setInterval(() => {
                    this.turn(1);
                }, this.props.delay * 1000);
                isSwipe = true;
            }else if (distanceX < -20){
                clearInterval(this.autoPlayFlag);
                this.turn(-1);
                this.autoPlayFlag = setInterval(() => {
                    this.turn(1);
                }, this.props.delay * 1000);
                isSwipe = true;
            }
        }else {
            if (distanceY > 20){
                isSwipe = true;
            }else if (distanceY < -20){
                isSwipe = true;
            }
        }

        // if (isSwipe){
        //     console.log('fire swipe event');
        // }
    },
    render(){
        let count = this.props.items.length;
        var _run = this.run;
        return (
                <div className="component-carousel" ref="swiper"
                     onTouchStart={this.touchStart}
                     onTouchMove={this.touchMove}
                     onTouchEnd={this.touchEnd}>
                    <div className="carousel-item-box">
                        <SliderItem items={this.props.items} nowLocal={this.state.nowLocal} />
                    </div>

                    <div className="no-flex">
                        {this.props.dots?<SliderDots count={count} nowLocal={this.state.nowLocal} turn={this.turn}/> : null}
                    </div>

                    {this.props.arrows? <SliderArrows turn={this.turn}/> : null}
                </div>
        )
    }
});

module.exports = Carousel;